package com.ruoyi.web.cp.service.rm;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.ruoyi.web.cp.domain.rm.RmGame;
import com.ruoyi.web.mapper.RmGameMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author xiesm
 * @Description: TODO
 * @date 2025-07-19 16:28
 */
@Service
public class RmGameService {
    @Autowired
    private RmGameMapper rmGameMapper;

    @Async
    public void saveRmGame(List<String> allGames) {
        RmGameMapper mapper = SpringUtil.getBean("rmGameMapper", RmGameMapper.class);
        mapper.deleteAllDuplicateGames();

        List<String> gameIds = mapper.selectRecentGames();

        RmGameService service = SpringUtil.getBean("rmGameService", RmGameService.class);
        for (String str : allGames) {
            String[] strs = str.split("\t");
            DateTime date = DateUtil.parse(strs[2], "yyyy-MM-dd HH:mm");
            RmGame rmGame = new RmGame(strs[0], date, strs[1], strs[3], strs[4]);
            service.saveOrDeleteByGameId(rmGame, mapper, gameIds);
        }
    }

    @Transactional
    public void saveOrDeleteByGameId(RmGame entity, RmGameMapper mapper, List<String> gameIds) {
        if (entity == null) {
            return;
        }
        //不存在则插入
        if (!gameIds.contains(entity.getGameId())) {
            mapper.insertRmGame(entity);
        }
    }

    public List<RmGame> getGamesByGameIds(List<String> gameIds) {
        return rmGameMapper.selectByGameIds(gameIds);
    }

    @Async
    public void saveRmGamePlv(RmGame rmGame) {
        RmGameMapper mapper = SpringUtil.getBean("rmGameMapper", RmGameMapper.class);
        mapper.updateOddsByGameId(rmGame);
    }
}
